package myHttp

import (
	"bytes"
	"encoding/json"
	"errors"
	"io/ioutil"
	"net/http"
)

func SendRequest(url string,data map[string]string,method string,addHeaders map[string]string)(resp []byte,err error){
	// 封装成json
	jsonData, err := json.Marshal(data)
	if err != nil {
		return
	}
	body := bytes.NewReader(jsonData)
	// 创建req
	req, err := http.NewRequest(method, url, body)
	if err != nil {
		return
	}
	req.Header.Add("Content-type","application/json")

	// 设置headers
	if len(addHeaders) > 0 {
		for k,v := range addHeaders{
			req.Header.Add(k,v)
		}
	}

	// 发送http 请求
	client := &http.Client{}
	response, err := client.Do(req)

	if err != nil {
		return
	}

	defer response.Body.Close()

	if response.StatusCode != 200 {
		err = errors.New("http status err")
		//glog.Errorf("sendRequest failed, url=%v, response status code=%d", url, response.StatusCode)
		return
	}

	// 结果获取
	resp,err = ioutil.ReadAll(response.Body)
	return
}
